package com.zdj.algorithm;

/**
 * @author zdj
 * @date 2024-06-06 17:41
 * 题目链接 https://leetcode.cn/problems/separate-black-and-white-balls/description/?envType=daily-question&envId=2024-06-06
 */
public class MinimumSteps {

    public long minimumSteps(String s) {
        char[] chars = s.toCharArray();

        long minimumSteps = getMinimumSteps(chars);

        while (!finished(chars)) {
            minimumSteps += getMinimumSteps(chars);
        }
        return minimumSteps;
    }

    public boolean finished(char[] chars) {
        if (areAllElements(chars, '0')) {
            return true;
        }
        if (areAllElements(chars, '1')) {
            return true;
        }
        String s = new String(chars);
        int i = s.indexOf("01") + 1;
        String a = s.substring(0, i);
        String b = s.substring(i);
        if (areAllElements(a.toCharArray(), '0') && areAllElements(b.toCharArray(), '1')) {
            return true;
        }
        return false;
    }

    public static boolean areAllElements(char[] array, char c) {
        if (array == null) {
            // 如果数组是null，那么返回false或者抛出异常，这取决于你的需求
            return false;
        }

        for (char element : array) {
            if (element != c) {
                // 如果发现任何一个元素不是0，就返回false
                return false;
            }
        }

        // 如果所有元素都遍历完且都是0，则返回true
        return true;
    }

    public long getMinimumSteps(char[] chars) {
        long result = 0;
        for (int i = 0; i < chars.length - 1; i++) {
            if (chars[i] == '1' && chars[i + 1] == '0') {
                char temp;
                temp = chars[i];
                chars[i] = chars[i + 1];
                chars[i + 1] = temp;
                result++;
            }
        }
        return result;
    }

    /**
     * 每个白球左边有多少黑球就要交换多少次
     */
    public long minimumSteps2(String s) {
        long ans = 0;
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '1') {
                sum++;
            } else {
                ans += sum;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new MinimumSteps().minimumSteps2("01101001"));
    }
}
